package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.io.PrintWriter;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        //TODO: [222024321072027/舒鑫] 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            //TODO: [222024321072027/舒鑫] 如果连DefaultHandler都没有，返回500 Internal Server Error
            try {
                PrintWriter writer = new PrintWriter(response);

                String content = "<h1>500 Internal Server Error</h1>" +
                        "<p>No handler available for the request.</p>";

                writer.println("HTTP/1.1 500 Internal Server Error");
                writer.println("Content-Type: text/html; charset=UTF-8");
                writer.println("Content-Length: " + content.getBytes().length);
                writer.println("Connection: close");
                writer.println();
                writer.println(content);
                writer.flush();
            } catch (Exception e) {
                System.err.println("无法发送500错误响应: " + e.getMessage());
            }
        }
    }
}
